﻿using System.Collections.Generic;
using System.Linq;
using Apps.Web.Core;
using Apps.Locale;
using System.Web.Mvc;
using Apps.Common;
using Apps.Models.PUB;
using Newtonsoft.Json;
using Apps.Models;
using Apps.BLL.HC;
using DocumentFormat.OpenXml.Spreadsheet;
using System;
using System.Text.RegularExpressions;

namespace Apps.Web.Areas.HC.Controllers
{
    public class HC_EXTEND_FIELDController : BaseController
    {
        HC_EXTEND_FIELD_BLL bll = new HC_EXTEND_FIELD_BLL();
        HC_ITEM_EXTEND_REL_BLL relBll = new HC_ITEM_EXTEND_REL_BLL();
        HC_FIELD_REFERENCE_VALUE_BLL vBll = new HC_FIELD_REFERENCE_VALUE_BLL();
        ValidationErrors errors = new ValidationErrors();

        [SupportFilter]
        public ActionResult Index()
        {
            return View();
        }
        [HttpPost]
        [SupportFilter(ActionName = "Index")]
        public JsonResult GetList()
        {
            int totalCount = 0;
            string queryStr = Utils.ObjectToStr(Request["queryStr"]);
            int pageSize = Utils.ObjToInt(Request["rows"], 15);
            int pageIndex = Utils.ObjToInt(Request["page"], 1);
            string sort = Utils.ObjectToStr(Request["sort"]);
            string order = Utils.ObjectToStr(Request["order"]);
            List<HC_EXTEND_FIELD> list = bll.GetList(queryStr, pageIndex, pageSize, sort, order, ref totalCount);
            return Json(new Pagination.PaginationResult<HC_EXTEND_FIELD>(totalCount, list.ToList()));
        }
        #region 创建
        [SupportFilter]
        public ActionResult Create()
        {
            return View();
        }

        [HttpPost]
        [SupportFilter]
        public JsonResult Create(EXTENDFIELD_REFERENCEVALUE model)
        {
            if (model != null && ModelState.IsValid)
            {
                if (string.IsNullOrEmpty (model.NAME))
                {
                    return Json(JsonHandler.CreateMessage(0, "请输入列名!"));
                }
                bool isTeshu = Regex.Replace(model.NAME, "[\\u4e00-\\u9FA5A-Za-z0-9]", "", RegexOptions.IgnoreCase).Length > 0;
                if (isTeshu)
                {
                    return Json(JsonHandler.CreateMessage(0, "化产项目别名不能包含特殊名称!"));
                }
                if (!Regex.IsMatch(model.NAME, @"^[A-Za-z]+$"))
                {
                    return Json(JsonHandler.CreateMessage(0, "列名只能是英文字符，建议输入拼音!"));
                }
                if (bll.AddIsRepeated(model.NAME))
                {
                    return Json(JsonHandler.CreateMessage(0, "已存在相同名称的列名!"));
                }

                string jsonstr = JsonConvert.SerializeObject(model);

                List<HC_FIELD_REFERENCE_VALUE> valueList = new List<HC_FIELD_REFERENCE_VALUE>();
                HC_EXTEND_FIELD extend_field_model = new HC_EXTEND_FIELD
                {
                    ID = model.ID,
                    TITLE = model.TITLE,
                    NAME = model.NAME.ToUpper(),
                    SORT = model.SORT,
                    ENABLE = model.ENABLE,
                    CONTROL_TYPE = model.CONTROL_TYPE,
                    IS_REQUIRED = model.IS_REQUIRED,
                    REMARK = model.REMARK,
                    ADDTIME = DateTime.Now,
                    ADDUSERID = GetUserId()
                };
                if (!string.IsNullOrEmpty(model.ReferenceValues))
                {
                    List<REFERENCE_VALUE> list = JsonHandler.DeserializeJsonToObject<List<REFERENCE_VALUE>>(model.ReferenceValues);
                    foreach (REFERENCE_VALUE reference_value in list)
                    {
                        valueList.Add(new HC_FIELD_REFERENCE_VALUE()
                        {
                            ID = ResultHelper.NewId,
                            EXTENDFIELDID = extend_field_model.ID,
                            BASEVALUE = reference_value.BASEVALUE,
                            MINVALUE = reference_value.MINVALUE,
                            MAXVALUE = reference_value.MAXVALUE,
                            ADDTIME = DateTime.Now,
                            ADDUSER = GetUserId()
                        });
                    }
                }
                if (bll.DoAdd(extend_field_model, valueList))
                {
                    LogHandler.WriteServiceLog(GetUserId(), jsonstr, "成功", "创建", "HC_EXTEND_FIELD");
                    return Json(JsonHandler.CreateMessage(1, Resource.InsertSucceed));
                }
                else
                {
                    string ErrorCol = errors.Error;
                    LogHandler.WriteServiceLog(GetUserId(), jsonstr, "失败", "创建", "HC_EXTEND_FIELD");
                    return Json(JsonHandler.CreateMessage(0, Resource.InsertFail + ErrorCol));
                }
            }
            else
            {
                return Json(JsonHandler.CreateMessage(0, Resource.InsertFail));
            }
        }

        [HttpPost]
        public JsonResult GetListDetail(string filedId)
        {
            //List<HC_FIELD_REFERENCE_VALUE> list = vBll.GetList(filedId);
            //return Json(list);
            EXTENDFIELD_REFERENCEVALUE entity = bll.GetEntityByID(filedId);
            List<REFERENCE_VALUE> list = null;
            if (entity != null)
            {
                list = JsonHandler.DeserializeJsonToObject<List<REFERENCE_VALUE>>(entity.ReferenceValues);
            }
            return Json(list);
        }
        #endregion


        #region 修改
        [SupportFilter]
        public ActionResult Edit(string filedId)
        {
            EXTENDFIELD_REFERENCEVALUE entity = bll.GetEntityByID(filedId);
            ViewData.Model = entity;
            return View(entity);
        }

        [HttpPost]
        [SupportFilter]
        public JsonResult Edit(EXTENDFIELD_REFERENCEVALUE model)
        {
            if (model != null && ModelState.IsValid)
            {
                if (string.IsNullOrEmpty(model.NAME))
                {
                    return Json(JsonHandler.CreateMessage(0, "请输入列名!"));
                }
                bool isTeshu = Regex.Replace(model.NAME, "[\\u4e00-\\u9FA5A-Za-z0-9]", "", RegexOptions.IgnoreCase).Length > 0;
                if (isTeshu)
                {
                    return Json(JsonHandler.CreateMessage(0, "列名不能包含特殊名称!"));
                }
                if(!Regex.IsMatch(model.NAME, @"^[A-Za-z]+$"))
                {
                    return Json(JsonHandler.CreateMessage(0, "列名只能是英文字符，建议输入拼音!"));
                }
                if (bll.EditIsRepeated(model.ID, model.NAME))
                {
                    return Json(JsonHandler.CreateMessage(0, "已存在相同名称的列名!"));
                }

                string jsonstr = JsonConvert.SerializeObject(model);

                HC_EXTEND_FIELD extendModel = bll.GetById(model.ID);
                extendModel.TITLE = model.TITLE;
                extendModel.SORT = model.SORT;
                extendModel.ENABLE = model.ENABLE;
                extendModel.CONTROL_TYPE = model.CONTROL_TYPE;
                extendModel.IS_REQUIRED = model.IS_REQUIRED;
                extendModel.REMARK = model.REMARK;
                extendModel.UPDATETIME = DateTime.Now;
                extendModel.UPDATEUSERID = GetUserId();

                List<HC_FIELD_REFERENCE_VALUE> valueList = vBll.GetList(model.ID);
                List<HC_FIELD_REFERENCE_VALUE> addvalueList = new List<HC_FIELD_REFERENCE_VALUE>();
                List<HC_FIELD_REFERENCE_VALUE> editvalueList = new List<HC_FIELD_REFERENCE_VALUE>();
                List<REFERENCE_VALUE> list = JsonHandler.DeserializeJsonToObject<List<REFERENCE_VALUE>>(model.ReferenceValues);

                foreach (REFERENCE_VALUE reference_value in list)
                {
                    if (valueList.Any(x => x.ID == reference_value.ID))
                    {
                        editvalueList.Add(new HC_FIELD_REFERENCE_VALUE()
                        {
                            ID = reference_value.ID,
                            BASEVALUE = reference_value.BASEVALUE,
                            MINVALUE = reference_value.MINVALUE,
                            MAXVALUE = reference_value.MAXVALUE,
                            EDITTIME = DateTime.Now,
                            EDITUSER = GetUserId(),
                        });
                    }
                    else
                    {
                        addvalueList.Add(new HC_FIELD_REFERENCE_VALUE()
                        {
                            ID = ResultHelper.NewId,
                            EXTENDFIELDID = model.ID,
                            BASEVALUE = reference_value.BASEVALUE,
                            MINVALUE = reference_value.MINVALUE,
                            MAXVALUE = reference_value.MAXVALUE,
                            ADDTIME = DateTime.Now,
                            ADDUSER = GetUserId(),
                        });
                    }
                }
                if (bll.DoEdit(extendModel, addvalueList, editvalueList))
                {
                    LogHandler.WriteServiceLog(GetUserId(), jsonstr, "成功", "修改", "HC_EXTEND_FIELD");
                    return Json(JsonHandler.CreateMessage(1, Resource.EditSucceed));
                }
                else
                {
                    string ErrorCol = errors.Error;
                    LogHandler.WriteServiceLog(GetUserId(), jsonstr, "失败", "修改", "HC_EXTEND_FIELD");
                    return Json(JsonHandler.CreateMessage(0, Resource.EditFail + ErrorCol));
                }
            }
            else
            {
                return Json(JsonHandler.CreateMessage(0, Resource.EditFail));
            }
        }
        #endregion

        #region 删除
        [HttpPost]
        [SupportFilter]
        public ActionResult Delete(string id)
        {
            if (!string.IsNullOrWhiteSpace(id))
            {
                if (relBll.IsHaveRel(id))
                {
                    string ErrorCol = "【该扩展列已被使用，禁止删除】";
                    LogHandler.WriteServiceLog(GetUserId(), "ID" + id + "," + ErrorCol, "失败", "删除", "HC_HC_EXTEND_FIELD");
                    return Json(JsonHandler.CreateMessage(0, Resource.DeleteFail + ErrorCol));
                }
                else
                {
                    if (bll.DoDelete(id))
                    {
                        LogHandler.WriteServiceLog(GetUserId(), "ID:" + id, "成功", "删除", "PUB_SUPPLIER");
                        return Json(JsonHandler.CreateMessage(1, Resource.DeleteSucceed));
                    }
                    else
                    {
                        string ErrorCol = "【删除失败】";
                        LogHandler.WriteServiceLog(GetUserId(), "ID" + id + "," + ErrorCol, "失败", "删除", "HC_HC_EXTEND_FIELD");
                        return Json(JsonHandler.CreateMessage(0, Resource.DeleteFail + ErrorCol));
                    }
                }
            }
            else
            {
                return Json(JsonHandler.CreateMessage(0, Resource.DeleteFail));
            }
        }
        #endregion
    }
}